package no.uib.hplims.views.search;

import no.uib.hplims.Controller;

import com.vaadin.event.FieldEvents;
import com.vaadin.event.FieldEvents.BlurEvent;
import com.vaadin.event.FieldEvents.FocusEvent;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;

public class QuickSearch extends HorizontalLayout {

	private static final long serialVersionUID = -1166014086060727624L;

	private Controller controller = null;

	private TextField searchBox = null;
	private Button searchButton = null;

	public QuickSearch(Controller c) {
		controller = c;

		setSpacing(true);
		setMargin(false, true, false, true);

		Label qs = new Label("Find: ");
		qs.setSizeUndefined();

		searchBox = new TextField();
		searchBox.addListener(new FieldEvents.FocusListener() {
			private static final long serialVersionUID = -1242094314413933201L;

			public void focus(FocusEvent event) {
				if (searchButton != null) {
					searchButton.setClickShortcut(KeyCode.ENTER);
				}
			}

		});

		searchBox.addListener(new FieldEvents.BlurListener() {
			private static final long serialVersionUID = 1L;

			public void blur(BlurEvent event) {
				if (searchButton != null) {
					searchButton.removeClickShortcut();
				}

			}
		});

		searchButton = new Button("Search");
		searchButton.addListener(clickListener);

		addComponent(qs);
		addComponent(searchBox);
		addComponent(searchButton);
		this.setComponentAlignment(qs, Alignment.MIDDLE_CENTER);
		this.setComponentAlignment(searchBox, Alignment.MIDDLE_CENTER);
		this.setComponentAlignment(searchButton, Alignment.MIDDLE_CENTER);
	}

	private ClickListener clickListener = new ClickListener() {

		private static final long serialVersionUID = 3660835856883162886L;

		public void buttonClick(ClickEvent event) {
			if (event.getButton() == searchButton) {
				controller.performQuickSearch((String) searchBox.getValue());
			}
		}

	};
}
